package net.mygwt.ui.client.widget;

import net.mygwt.ui.client.Events;
import net.mygwt.ui.client.Style;
import net.mygwt.ui.client.event.BaseEvent;
import net.mygwt.ui.client.event.Listener;
import net.mygwt.ui.client.fx.Draggable;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.SimplePanel;

public class DesktopShell extends Shell {

	private ModalPanel mModalPanel = new ModalPanel();
	private SimplePanel mDummy = new SimplePanel();

	public DesktopShell() {
		this(Style.CLOSE | Style.RESIZE);
	}

	public DesktopShell(int pStyle) {
		super(pStyle);
		mDummy.setVisible(false);
	}

	protected void onRender() {
		super.onRender();

		Listener dragListener = new Listener() {
			public void handleEvent(BaseEvent be) {
				switch (be.type) {
				case Events.DragStart:
					mModalPanel.show(mDummy);
					if (shadow != null) {
						shadow.setVisible(false);
					}
					break;
				case Events.DragEnd:
					if (shadow != null) {
						shadow.setVisible(true);
						shadow.sync(getBounds());
					}
					mModalPanel.hide();

					DeferredCommand.addCommand(new Command() {
						public void execute() {
							ShellManager.get().setActive(DesktopShell.this);
						}
					});

					// split bars are added to rootpanel and will not get
					// updated when shell is moved.
					SplitBar.updateHandles();
					break;
				}
			}
		};

		Draggable draggable = getDraggable();
		// draggable.useProxy = true;
		draggable.addListener(Events.DragStart, dragListener);
		draggable.addListener(Events.DragEnd, dragListener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.mygwt.ui.client.widget.Component#hide()
	 */
	public void hide() {
		super.hide();
		if (shadow != null && !isVisible()) {
			shadow.hide();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.mygwt.ui.client.widget.Component#show()
	 */
	public void show() {
		super.show();
		if (shadow != null && isVisible()) {
			shadow.show();
		}
	}

}
